package com.leon.ikun.ui.activities;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.net.Uri;
import android.view.View;
import android.widget.Toast;

import androidx.core.view.GravityCompat;
import androidx.lifecycle.Observer;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.viewbinding.ViewBinding;

import com.leon.ikun.R;
import com.leon.ikun.base.baseActivity.BaseActivity;
import com.leon.ikun.beans.account.AccountNav;
import com.leon.ikun.beans.home.AccountViewModel;
import com.leon.ikun.beans.home.HomeRecommendApp;
import com.leon.ikun.databinding.ActivityMainBinding;
import com.leon.ikun.http.ApiHelper;
import com.leon.ikun.http.BaseUrl;
import com.leon.ikun.http.HttpApi;
import com.leon.ikun.http.RetrofitClient;
import com.leon.ikun.ui.activities.drawerFunction.SettingActivity;
import com.leon.ikun.ui.activities.search.SearchActivity;
import com.leon.ikun.ui.adapters.JsHomeRecommendAdapter;
import com.leon.ikun.ui.dialogs.TipDialog;
import com.leon.ikun.ui.widget.loader.PaginationLoader;
import com.leon.ikun.utils.DataStoreUtils;
import com.leon.ikun.utils.PreferenceUtils;
import com.leon.ikun.utils.Utils;
import com.leon.ikun.utils.ViewUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ScheduledThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

import io.reactivex.rxjava3.core.Observable;

/**
 * @Author Leon
 * @Time 2021/10/30
 * @Desc
 */
public class MainActivity extends BaseActivity<ActivityMainBinding> {
    private ScheduledThreadPoolExecutor scheduledThreadPoolExecutor;
    public static AccountViewModel model;
    private HttpApi recommendHttpApi;

    private int pageNum  ;

    @Override
    public ActivityMainBinding getViewBinding() {
        return ActivityMainBinding.inflate(getLayoutInflater());
    }

    @SuppressLint("ClickableViewAccessibility")
    @Override
    protected void init() {
        binding.home.logo.setOnClickListener(v -> binding.home.data.container.content.scrollToPosition(0));
        binding.home.userFace.setOnClickListener(v -> binding.getRoot().openDrawer(GravityCompat.START));
        binding.home.search.setOnClickListener(v -> startActivity(SearchActivity.class));
        binding.drawer.userContainer.setOnTouchListener((v, event) -> ViewUtils.zoom(event, binding.drawer.userContainer));
//        binding.drawer.userContainer.setOnClickListener(v -> startActivity(LoginActivity.class));
        binding.drawer.userLogout.setOnClickListener(v -> {
            TipDialog tipDialog = new TipDialog(context);
            tipDialog.setTitle("退出");
            tipDialog.setContent("是否要退出当前账户？");
            tipDialog.setActionStr("取消", "退出");
            tipDialog.setOnActionListener(action -> {
                if (action) {
                    localAccountStatus(null);
                }

                tipDialog.dismiss();
            });
            tipDialog.show();
        });


        setDrawerFunctionListener();

        recommendHttpApi = new RetrofitClient(BaseUrl.JSAPP, context).getHttpApi();

        boolean loginStatus = PreferenceUtils.getLoginStatus(context);
        if (!loginStatus) {
            initObserver();
        }

        // 首次调用nav接口，获取Wbi数据
        refreshData();

        PaginationLoader<HomeRecommendApp, HomeRecommendApp.VodInfo> loader;
        int recommendStyle = PreferenceUtils.getRecommendStyle(context);
        if (recommendStyle == 1) {
            loader = new PaginationLoader<>(binding.home.data, new JsHomeRecommendAdapter(context));
        } else {
            loader = new PaginationLoader<>(binding.home.data, new JsHomeRecommendAdapter(context), new GridLayoutManager(context, 2));
        }
        loader.enabledRefresh(true);
        loader.setGuide(homeRecommend -> {
            List<HomeRecommendApp.VodInfo> list = homeRecommend.getList();
            return list;
        });
        loader.setUpdateInterface(loadType -> {
            Observable<HomeRecommendApp> homeRecommendAppJisu = recommendHttpApi.getHomeRecommendAppJisu(++pageNum);
            return homeRecommendAppJisu;
        });
        loader.firstObtain();

        Utils.CheckUpdate(context, false);
    }

    /**
     * drawer function action
     */
    private void setDrawerFunctionListener() {
//        binding.drawer.popular.setOnClickListener(v -> startPage(PopularActivity.class));
//        binding.drawer.partition.setOnClickListener(v -> startPage(PartitionActivity.class));
//        binding.drawer.channel.setOnClickListener(v -> startPage(ChannelActivity.class));
//        binding.drawer.orders.setOnClickListener(v -> startPage(OrderActivity.class));
//        binding.drawer.favorites.setOnClickListener(v -> startPage(FavoriteActivity.class));
//        binding.drawer.later.setOnClickListener(v -> startPage(WatchLaterActivity.class));
//        binding.drawer.follows.setOnClickListener(v -> startPage(RelationActivity.class));
//        binding.drawer.history.setOnClickListener(v -> startPage(HistoryActivity.class));
//        binding.drawer.download.setOnClickListener(v -> startPage(DownloadActivity.class));
        binding.drawer.settings.setOnClickListener(v -> startPage(SettingActivity.class));
        binding.drawer.qq.setOnClickListener(v -> {
            Intent intent = new Intent();
            intent.setData(Uri.parse("mqqopensdkapi://bizAgent/qm/qr?url=http%3A%2F%2Fqm.qq.com%2Fcgi-bin%2Fqm%2Fqr%3Ffrom%3Dapp%26p%3Dandroid%26jump_from%3Dwebapi%26k%3D" + "cCZ5md53wsk-Ha3CrMrAYvkYxOJl8_bf"));
            try {
                context.startActivity(intent);
            } catch (Exception e) {
                Toast.makeText(context, "调起QQ失败，请检查QQ是否为最新版或是否已安装QQ", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * start the DataListActivity
     */
    private void startPage(Class<? extends BaseActivity<? extends ViewBinding>> targetClass) {
        startActivity(targetClass);
        delayCloseDrawer();
    }

    /**
     * delay closing the drawer
     */
    private void delayCloseDrawer() {
        if (scheduledThreadPoolExecutor == null) {
            scheduledThreadPoolExecutor = new ScheduledThreadPoolExecutor(1, r -> new Thread(r, "delayCloseDrawer"));
        }

        scheduledThreadPoolExecutor.schedule(() -> binding.getRoot().closeDrawer(GravityCompat.START), 800, TimeUnit.MILLISECONDS);
    }

    /**
     * 初始化观察者对象
     */
    private void initObserver() {
        model = new ViewModelProvider(this).get(AccountViewModel.class);
        model.getLoginStatus().observeForever(new Observer<>() {
            @Override
            public void onChanged(Boolean loginStatus) {
                if (loginStatus) {
                    refreshData();

                    model.getLoginStatus().removeObserver(this);
                    model = null;
                }
            }
        });
    }

    /**
     * 获取已登录用户数据
     */
    private void refreshData() {
        new ApiHelper<>(new RetrofitClient(BaseUrl.API, context).getHttpApi().getAccountInfo())
                .setOnResult(accountNav -> {
                    recommendHttpApi = new RetrofitClient(BaseUrl.JSAPP, context).getHttpApi();
                    localAccountStatus(accountNav);
                }).doIt();
    }

    /**
     * 登录/退出 操作
     *
     * @param accountNav accountNav
     */
    private void localAccountStatus(AccountNav accountNav) {

        // 退出当前账户
        if (accountNav == null) {
            DataStoreUtils.INSTANCE.clearSync(context);
            binding.drawer.userContainer.setEnabled(true);
            binding.drawer.userFace.setImageResource(R.drawable.user_face_default);
            binding.home.userFace.setImageResource(R.drawable.user_face_default);
            binding.drawer.userName.setText("");
            binding.drawer.userLogout.setVisibility(View.GONE);

            // 登录成功
        } else {
            if (accountNav.getData().isLogin()) {
                PreferenceUtils.setVipStatus(context, accountNav.getData().getVipStatus() != 0);
                binding.drawer.userContainer.setEnabled(false);
                ViewUtils.setImg(context, binding.drawer.userFace, accountNav.getData().getFace());
                ViewUtils.setImg(context, binding.home.userFace, accountNav.getData().getFace());
                binding.drawer.userName.setText(accountNav.getData().getUname());
                binding.drawer.userLogout.setVisibility(View.VISIBLE);

                // 获取csrf
                if ("".equals(PreferenceUtils.getCsrf(context))) {
                    String[] split = PreferenceUtils.getCookie(context).split("; ");
                    Map<String, String> cookieMap = new HashMap<>(split.length);
                    for (String s : split) {
                        String[] arrayTemp = s.split("=");
                        cookieMap.put(arrayTemp[0], arrayTemp[1]);
                    }

                    PreferenceUtils.setCsrf(context, cookieMap.get("bili_jct"));
                }
            }

            AccountNav.Data.WbiImg wbiImg = accountNav.getData().getWbiImg();
            PreferenceUtils.setImgKey(context,
                    wbiImg.getImgUrl().substring(wbiImg.getImgUrl().lastIndexOf("/") + 1, wbiImg.getImgUrl().lastIndexOf(".")));
            PreferenceUtils.setSubKey(context,
                    wbiImg.getSubUrl().substring(wbiImg.getSubUrl().lastIndexOf("/") + 1, wbiImg.getSubUrl().lastIndexOf(".")));

        }
    }
}